//
//  RadioPlayViewController.m
//  PetTown
//
//  Created by lanou3g on 15/6/1.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "RadioPlayViewController.h"
#import "UIImageView+WebCache.h"
#import "AppDelegate.h"
@interface RadioPlayViewController ()<AVAudioPlayerDelegate>


@end

@implementation RadioPlayViewController

-(void)dealloc{
    //从消息中心注销
    [[NSNotificationCenter defaultCenter] removeObserver:self name:RadioOver object:nil];
}


-(void)loadView{
    self.radioPV = [[RadioPlayView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.view = _radioPV;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setTranslucent:NO];
    // Do any additional setup after loading the view.
    //上一曲
    [_radioPV.lastButton addTarget:self action:@selector(lastClick:) forControlEvents:UIControlEventTouchDown];
    //播放or暂停
    [_radioPV.playButton addTarget:self action:@selector(playORstopClick:) forControlEvents:UIControlEventTouchDown];
    //下一曲
    [_radioPV.nextButton addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchDown];
    //控制播放进度
    [_radioPV.playSlider addTarget:self action:@selector(sliderClick:) forControlEvents:UIControlEventValueChanged];
    //播放完毕的消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nextRadio) name:RadioOver object:nil];
    
    //设置changeView为隐藏
    AppDelegate * app = (AppDelegate * )[UIApplication sharedApplication].delegate;
    app.changeView.hidden = YES;
    
    
    [self setLeftBI];
    [self setViewData];
    [self setAVPlayer];


}

//设置左边BI
- (void)setLeftBI{
    UIButton * retunButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    retunButton.frame = CGRectMake(0, 0, 32, 32);
    [retunButton setBackgroundImage:[UIImage imageNamed:@"ReturnPage.png"] forState:UIControlStateNormal];
    [retunButton addTarget:self action:@selector(leftBIClick) forControlEvents:UIControlEventTouchDown];
        UIBarButtonItem * leftBI = [[UIBarButtonItem alloc] initWithCustomView:retunButton];
    self.navigationItem.leftBarButtonItem = leftBI;
    self.navigationItem.title = @"一个故事一种心情";
    
    
    
}

//BI事件
- (void)leftBIClick{
    [_audioPlayer pause];
    [_audioPlayer replaceCurrentItemWithPlayerItem:nil];
    _avPlayerItem = nil;
    _audioPlayer=nil;
    [self.navigationController popViewControllerAnimated:YES];
    //设置changeView为显示
    AppDelegate * app = (AppDelegate * )[UIApplication sharedApplication].delegate;
    app.changeView.hidden = NO;
}
//赋值
-(void)setViewData{
    //设置标题
    self.radioPV.titleLabel.text = _titleArray[_index];
    NSURL * url = [NSURL URLWithString:_radioImgUrlArray[_index]];
    [_radioPV.photoImg sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"place.jpg"]];
}

//新建avplayer
- (void)setAVPlayer{
    self.urlStr = _radioUrlArray[_index];
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    self.avPlayerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_urlStr]];
    self.audioPlayer = [AVPlayer playerWithPlayerItem:_avPlayerItem];
   
}

//定时器
-(NSTimer *)timer{
    if (!_timer) {
        _timer=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateProgress) userInfo:nil repeats:true];
    }
    return _timer;
}


//设置显示时间
- (void)initTimelabel
{
    //更新显示的时间
    NSString *currentTime = [self formatDateWithSecond:(int)_currentDuration];
    NSString *totalTime = [self formatDateWithSecond:(int)_totalDuration];
    NSString *timeString = [NSString stringWithFormat:@"%@ / %@",currentTime,totalTime];
    _radioPV.timeLabel.text = timeString;
}
//时间格式
- (NSString *)formatDateWithSecond:(int)second
{
    if(!second || second<=0){
        return @"00:00";
    }
    int hour = second/(60*60);
    int minute = (second-(60*60)*hour)/60;
    second -= (60*60)*hour+minute*60;
    
    if(hour!=0){
        return [NSString stringWithFormat:@"%02i:%02i:%02i", hour, minute, second];
    }else{
        return [NSString stringWithFormat:@"%02i:%02i", minute, second];
    }
    return nil;
}

// 更新播放进度
-(void)updateProgress{

//    //显示时间
    [self initTimelabel];
//    //显示缓冲进度
    [self setBuffer];
    //总时间
    _totalDuration=CMTimeGetSeconds(_audioPlayer.currentItem.duration);
    //当前时间
    _currentDuration=CMTimeGetSeconds(_audioPlayer.currentItem.currentTime);
    
    self.radioPV.playSlider.value = _currentDuration/_totalDuration;
    //判断是否播放完成
    if ( _totalDuration > 0 &&(_totalDuration - _currentDuration)<1) {
        //发消息,通知播放完成
        [[NSNotificationCenter defaultCenter] postNotificationName:RadioOver object:nil];
    }
    
}


//更行缓存进度
- (void)setBuffer{
    NSArray *loadedTimeRanges = [[self.audioPlayer currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval timeInterval = startSeconds + durationSeconds;// 计算缓冲总进度
    CMTime duration = self.audioPlayer.currentItem.duration;
    CGFloat totalDuration = CMTimeGetSeconds(duration);
    [self.radioPV.bufferView setProgress:timeInterval / totalDuration animated:YES];
} 

//控制播放进度
- (void)sliderClick:(UISlider *)slider{
    
    [_audioPlayer seekToTime:CMTimeMakeWithSeconds(_radioPV.playSlider.value * _totalDuration, 1)];

}
//上一曲
- (void)lastRadio{
    if (_index >0) {
        _index --;
    }else{
        _index = _radioUrlArray.count - 1;
    }
    //重置图片
    NSURL * url = [NSURL URLWithString:_radioImgUrlArray[_index]];
    [_radioPV.photoImg sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Stars@2x.png"]];
    //重置标题
    self.radioPV.titleLabel.text = _titleArray[_index];
    //重置歌曲
    self.urlStr = _radioUrlArray[_index];
    //重置Item
    _avPlayerItem = nil;
    [_audioPlayer replaceCurrentItemWithPlayerItem:nil];
    self.avPlayerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_urlStr]];
    [_audioPlayer replaceCurrentItemWithPlayerItem:_avPlayerItem];
    [_audioPlayer play];
}
//下一曲
- (void)nextRadio{
    if (_index <_radioUrlArray.count - 1) {
        _index ++;
    }else{
        _index = 0;
    }
    //重置图片
    NSURL * url = [NSURL URLWithString:_radioImgUrlArray[_index]];
    [_radioPV.photoImg sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Stars@2x.png"]];
    //重置标题
    self.radioPV.titleLabel.text = _titleArray[_index];
    //重置歌曲
    self.urlStr = _radioUrlArray[_index];
    //重置Item
    _avPlayerItem = nil;
    [_audioPlayer replaceCurrentItemWithPlayerItem:nil];
    self.avPlayerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_urlStr]];
    [_audioPlayer replaceCurrentItemWithPlayerItem:_avPlayerItem];
    [_audioPlayer play];
}

//上一曲
-(void)lastClick:(UIButton *)button{
    [self lastRadio];
}
//播放or暂停
-(void)playORstopClick:(UIButton *)button{
    if (self.audioPlayer.rate == 1) {
        [self.audioPlayer pause];
        [button setBackgroundImage:[UIImage imageNamed:@"PauseRadio.png"] forState:UIControlStateNormal];
        self.timer.fireDate=[NSDate distantFuture];//暂停定时器
    } else {
        [self.audioPlayer play];
        [button setBackgroundImage:[UIImage imageNamed:@"PlayRadio.png"] forState:UIControlStateNormal];
        self.timer.fireDate=[NSDate distantPast];//恢复定时器
    }
}
//下一曲
-(void)nextClick:(UIButton *)button{
    [self nextRadio];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    //清除缓存
    SDImageCache * sdI = [SDImageCache sharedImageCache];
    [sdI clearDisk];
    [sdI clearMemory];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
